package com.gg.goods;

import com.gg.entity.Fruit;
import com.gg.helper.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@WebServlet(name = "GetFruitsByEntranceServlet", value = "/goods/GetFruitsByEntranceServlet")
public class GetFruitsByEntranceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*获取请求参数f_entrance*/
//        boolean  f_entrance = Boolean.parseBoolean(request.getParameter("f_entrance"));
        boolean  f_entrance = false ; //默认
        String  str  =  request.getParameter("f_entrance");
        if(str.equals("1")){
            f_entrance = true ;
        }else{
            f_entrance=false ;
        }
        /*创建一个Fruit 集合*/
        List<Fruit> fruits =  new ArrayList<>();
        /*1.数据库 连接*/
        Connection  con = DBHelper.getConnection();
        /*2. SQL */
        String  sql  ="select *  from fruit where f_entrance = ? ";
        /*3. 发射器*/
        try {
            PreparedStatement  ps =  con.prepareStatement(sql);
            /*4.*/
            ps.setBoolean(1,f_entrance);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                int  f_id = rs.getInt("f_id");
                String  f_name = rs.getString("f_name");
                String  f_norm = rs.getString("f_norm");
                BigDecimal f_price = rs.getBigDecimal("f_price");
                String  f_summary = rs.getString("f_summary");
                String  f_prompt = rs.getString("f_prompt");
                int  f_imgcount = rs.getInt("f_imgcount");
                String  c_id = rs.getString("c_id");
                f_entrance = rs.getBoolean("f_entrance");
                boolean  f_hot = rs.getBoolean("f_hot");
                //恢复一个水果
                Fruit fruit =  new Fruit(f_id,f_name,f_norm,f_price,f_summary,f_prompt,f_imgcount,c_id,f_entrance,f_hot);
                //把这个恢复出来的水果放集合里
                fruits.add(fruit);
            }
            /*把20个水果的   集合fruits 放Session里， 跳转页面到sel.jsp页面显示*/
            request.getSession().setAttribute("fruits",fruits);
            response.sendRedirect("/fruit/sel.jsp");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
